<?php

namespace App\Http\Middleware;

use App\Repositories\UsersRepository;
use App\ZL\Library\ErrorCode;
use Closure;
use Illuminate\Support\Facades\Auth;

class CheckWechatLogin
{

    const AUTH_KEY = 'home_auth_uid';

    public function isWechat()
    {
        return strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false;
    }

    public function goWechatAuthorize()
    {
//        session('authorize_before_url',\request()->fullUrl());
        //引导用户进入授权页面同意授权，获取code
        $redirect_url = "http://www.zidongdaxin.com/Home/Wechat/goFzcrmWechatAuthorize?url=".urlencode(\request()->fullUrl());
        header("location:$redirect_url");
        die();
    }
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $uid = session(self::AUTH_KEY);
        $auth = \request('auth');
        if(!$uid){
            if($auth){
                $auth = urldecode($auth);
                $auth = json_decode($auth,true);
                $uid = app(UsersRepository::class)->checkHasAndSaveInfo($auth);
                if($uid){
                    \Auth::loginUsingId($uid);
                    session([self::AUTH_KEY=>$uid]);
                    app('session')->save();
                }
            }else{
                if($this->isWechat())
                    $this->goWechatAuthorize();
            }
        }else{
            $user = \Auth::loginUsingId($uid);
            if(!$user && $this->isWechat())
                $this->goWechatAuthorize();
        }

        return $next($request);
    }
}
